<?php

namespace app\airobot\controller;

use app\airobot\FundConst;
use app\airobot\model\UserModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 超管系统-充值管理
 * Class Profit
 * @package app\airobot\controller
 */
class Profit extends Controller
{
    private $table = 'user_recharge';

    /**
     * 充值管理
     * @auth true
     */
    public function index()
    {
        $query = "";
        try {
            if ($this->request->isGet()) {
                $this->stime = $this->get['stime'] ?? '';
                $this->etime = $this->get['etime'] ?? '';
                $this->cam = $this->get['cam'] ?? '';
                $this->pay = $this->get['pay'] ?? '';

                if ($this->cam != '') {
                    $query = " cam = '" . $this->cam . "'";
                }

                if ($this->pay != '') {
                    if ($query == '') {
                        $query = $query . " pay = '" . $this->pay . "'";
                    } else {
                        $query = $query . " and pay = '" . $this->pay . "'";
                    }
                }
            }

            $date = [];
            $now = time();
            if ($this->stime != "" || $this->etime != "") {
                $today = date("Y-m-d");
                $stimeInterval = 0;
                if ($this->stime != "") {
                    $stimeInterval = $this->diffBetweenTwoDays($today, $this->stime);
                }
                $etimeInterval = 0;
                if ($this->etime != "") {
                    $etimeInterval = $this->diffBetweenTwoDays($today, $this->etime);
                }

                if ($stimeInterval == 0) {
                    $stimeInterval = $etimeInterval + 9;
                }

                for ($i = $etimeInterval; $i < $stimeInterval + 1; $i++) {
                    $s = "-" . $i . " day 00:00:00";
                    $day = date('Y-m-d', strtotime($s, $now));

                    $dateList = [];
                    for ($j = $i; $j >= 0; $j--) {
                        $s1 = "-" . $j . " day 00:00:00";
                        $day1 = date('Y-m-d', strtotime($s1, $now));
                        $dateListItem['day_name'] = 'day' . ($i - $j);
                        $dateListItem['day'] = $day1;
                        $dateList[] = $dateListItem;
                    }
                    $date[] = ['day' => $day, 'date_list' => $dateList];
                }
            } else {
                for ($i = 0; $i < 10; $i++) {
                    $s = "-" . $i . " day 00:00:00";
                    $day = date('Y-m-d', strtotime($s, $now));

                    $dateList = [];
                    for ($j = $i; $j >= 0; $j--) {
                        $s1 = "-" . $j . " day 00:00:00";
                        $day1 = date('Y-m-d', strtotime($s1, $now));
                        $dateListItem['day_name'] = 'day' . ($i - $j);
                        $dateListItem['day'] = $day1;
                        $dateList[] = $dateListItem;
                    }
                    $date[] = ['day' => $day, 'date_list' => $dateList];
                }
            }

            $resultList = [];
            foreach ($date as $value) {
                $day = $value['day'];
                $listItem = [];
                $listItem['id'] = 1;
                $listItem['day'] = $day;

                // 新增用户
                $sql = "";
                if ($query == '') {
                    $sql = "select id from users where created_at > '" . $day . " 00:00:00" . "' and created_at < '" . $day . " 23:59:59" . "'";
                } else {
                    $sql = "select id from users where " . $query . " and created_at > '" . $day . " 00:00:00" . "' and created_at < '" . $day . " 23:59:59" . "'";
                }
                $todayAddUsers = Db::query($sql);
                $listItem['new_user_count'] = count($todayAddUsers);
                if ($listItem['new_user_count'] == 0) {
                    $listItem['all_profit'] = 0;
                    $listItem['day0'] = 0;
                    $listItem['day1'] = 0;
                    $listItem['day2'] = 0;
                    $listItem['day3'] = 0;
                    $listItem['day4'] = 0;
                    $listItem['day5'] = 0;
                    $listItem['day6'] = 0;
                    $listItem['day7'] = 0;
                    $listItem['day8'] = 0;
                    $listItem['day9'] = 0;
                    $listItem['day10'] = 0;
                    $listItem['day11'] = 0;
                    $listItem['day12'] = 0;
                    $listItem['day13'] = 0;
                    $listItem['day14'] = 0;
                } else {
                    $userIds = [];
                    foreach ($todayAddUsers as $user) {
                        $userIds[] = $user['id'];
                    }
                    $userIdStr = implode(",", $userIds);

                    // 累计收益
                    $sql = "select sum(total_commission_amount) as totalCommissionAmount from `private_fund_order_v2` where `user_id` in (" . $userIdStr . ") group by order_id";
                    $totalCommissionAmount = Db::query($sql);
                    $allProfit = "0";
                    if (count($totalCommissionAmount) > 0) {
                        $allProfit = $this->dealAmount($totalCommissionAmount[0]['totalCommissionAmount']);
                    }
                    $listItem['all_profit'] = $allProfit;

                    // day0-day14的盈利数据
                    foreach ($value['date_list'] as $dateList) {
                        $dateListDay = $dateList['day'];
                        $sql = "select sum(total_commission_amount) as totalCommissionAmount from `private_fund_order_v2` where  created_at > '" . $dateListDay . " 00:00:00" . "' and created_at < '" . $dateListDay . " 23:59:59" . "'  and `user_id` in (" . $userIdStr . ") group by order_id";
                        $totalCommissionAmount = Db::query($sql);
                        $allProfit = "0";
                        if (count($totalCommissionAmount) > 0) {
                            $allProfit = $this->dealAmount($totalCommissionAmount[0]['totalCommissionAmount']);
                        }
                        $listItem[$dateList['day_name']] = $allProfit;

                     /*   if ($dateList['day_name'] == "day0") {
                            $sql = "select count(1) as ct from `user_recharge` where  created_at > '" . $dateListDay . " 00:00:00" . "' and created_at < '" . $dateListDay . " 23:59:59" . "'  and `user_id` in (" . $userIdStr . ")";
                            $chargeCount = Db::query($sql);
                            $listItem["ARPPU"] = $allProfit / $chargeCount[0]['ct'];
                            $listItem["ffl"] = round($chargeCount[0]['ct'] / $listItem['new_user_count'], 4) * 100 . "%";
                        }*/

                        $listItem["ARPPU"] = 0;
                        $listItem["ffl"] =0;
                    }
                }

                $resultList[] = $listItem;
            }
        } catch (\Exception $exception) {
           $this->error($exception->getMessage());
        }

        $result = ['list' => $resultList];
        $this->fetch("index", $result);
    }

    public function dealAmount($value, $isCny = false)
    {
        if ($value == null) {
            return 0;
        }

        if (!$isCny) {
            $value = $value * $this->cnyRate;
        }
        if ($value < 1) {
            return $this->getPrecision($value, 1);
        }

        $decimal = 0;
        if ($value < 100) {
            $decimal = 2;
        }
        return number_format($value, $decimal, '.', ',');
    }

    public function getPrecision($value, $precision)
    {
        if ($value == 0) {
            return $value;
        }
        $valueResult = number_format($value, $precision);
        while ($valueResult == 0) {
            if ($precision >= 8) {
                return 0;
            }
            $precision++;
            $valueResult = number_format($value, $precision);
        }

        if ($precision < 4) {
            $valueResult = number_format($value, 4);
        }

        return $valueResult;
    }

    function diffBetweenTwoDays($day1, $day2)
    {
        // 将日期字符串转换为 Unix 时间戳（秒数）
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        // 确保 $second1 永远是较大的时间戳
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }

        // 计算两个时间戳之间的秒数差值
        // 86400 是一天的秒数 (24小时 * 60分钟 * 60秒)
        // 使用 intval() 函数将结果转换为整数（向下取整）
        return intval(($second1 - $second2) / 86400);
    }
}